﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Top.Data;
using Top.Core;
using Top.Common;

namespace Top.PointStore.Business
{
    public class PointRuleManager
    {
        /// <summary>
        /// 根据行为代码判断该行为是否启用
        /// </summary>
        /// <param name="pointCode"></param>
        /// <returns></returns>
        public static async Task<T_PointRule> Get(string pointCode)
        {
            const string sql = "select * from T_PointRule where F_PointCode={0} and F_Status=1";
            using (var db = new DbTour())
            {
                return await db.Sql(sql, pointCode).FirstOrDefault<T_PointRule>();
            }
        }

        /// <summary>
        /// 添加积分规则
        /// </summary>
        /// <param name="pointCode">行为标识</param>
        /// <param name="pointAction">触发行为</param>
        /// <param name="point">积分数</param>
        /// <param name="status">状态</param>
        /// <param name="sort">排序号</param>
        /// <param name="adminKid">操作人ID</param>
        /// <returns>添加成功返回true</returns>
        public static async Task<bool> Create(string pointCode, string pointAction, int point, int status, int sort, int adminKid)
        {
            if (string.IsNullOrEmpty(pointAction))
                throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "触发行为不能为空!");
            if (string.IsNullOrEmpty(pointCode))
                throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "行为标识不能为空!");
            using (var db = DataBaseContext.GetDataBase("default"))
            {
                const string existsCodeSql = "SELECT COUNT(1) FROM t_pointrule WHERE F_PointCode={0}";
                int existsCode = await db.Sql(existsCodeSql, pointCode).ExecuteScalar<int>();
                if (existsCode > 0)
                {
                    throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "行为标识已存在!");
                }

                const string createSql =
                    "INSERT INTO t_pointrule (F_PointCode,F_PointAction,F_Point,F_Status,F_Sort,F_AddTime,F_AddAdminKid)" +
                    " VALUES ({0},{1},{2},{3},{4},{5},{6})";
                return await db.Sql(createSql, pointCode, pointAction, point, status, sort, DateTime.Now, adminKid)
                    .ExecuteNonQuery() > 0;
            }
        }


        /// <summary>
        /// 删除积分规则
        /// </summary>
        /// <param name="pointRuleKidList">要删除的积分规则Kid列表</param>
        /// <returns></returns>
        public static async Task<bool> Delete(int pointRuleKid)
        {
            if (pointRuleKid <= 0)
                throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "请选择要删除的项!");
            using(var db = DataBaseContext.GetDataBase("default"))
            {
                const string sql =
                    "DELETE FROM t_pointrule WHERE Kid={0}";
                return await db.Sql(sql, pointRuleKid).ExecuteNonQuery() > 0;
            }
        }


        /// <summary>
        /// 积分规则修改
        /// </summary>
        /// <param name="pointRuleKid">积分规则id</param>
        /// <param name="pointCode">行为标识</param>
        /// <param name="pointAction">触发行为</param>
        /// <param name="point">积分数</param>
        /// <param name="status">状态</param>
        /// <param name="sort">排序号</param>
        /// <param name="adminKid">操作人ID</param>
        /// <returns>修改成功返回true</returns>
        public static async Task<bool> Edit
            (int pointRuleKid, string pointCode, string pointAction, int point, bool status, int sort, int adminKid)
        {
            if (pointRuleKid <= 0)
                throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "参数错误!");
            if (string.IsNullOrEmpty(pointAction))
                throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "触发行为不能为空!");
            if (string.IsNullOrEmpty(pointCode))
                throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "行为标识不能为空!");

            using(var db = DataBaseContext.GetDataBase("default"))
            {
                const string existsCodeSql =
                    "SELECT COUNT(1) FROM t_pointrule WHERE F_PointCode={0} AND Kid<>{1}";
                int existsCode = await db.Sql(existsCodeSql, pointCode, pointRuleKid).ExecuteScalar<int>();
                if (existsCode > 0)
                {
                    throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "行为标识已存在!");
                }

                const string updateSql =
                    "UPDATE t_pointrule SET F_PointCode={0},F_PointAction={1},F_Point={2},F_Status={3},F_Sort={4}," +
                    "F_EditAdminKid={5},F_EditTime={6} WHERE Kid={7}";
                return await db.Sql(updateSql, pointCode, pointAction, point, status, sort, adminKid, DateTime.Now, pointRuleKid)
                    .ExecuteNonQuery() > 0;
            }
        }

        /// <summary>
        /// 根据ID获取一条积分规则
        /// </summary>
        /// <param name="pointRuleKid">积分规则id</param>
        /// <returns>积分规则对象</returns>
        public static async Task<T_PointRule> Retrieve(int pointRuleKid)
        {
            if (pointRuleKid <= 0)
                throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "参数错误!");
            using(var db = DataBaseContext.GetDataBase("default"))
            {
                const string sql = "SELECT * FROM t_pointrule WHERE Kid={0}";
                return await db.Sql(sql, pointRuleKid).FirstOrDefault<T_PointRule>();
            }
        }

        /// <summary>
        /// 积分规则列表
        /// </summary>
        /// <param name="keyword">搜索关键字，可以是行为标识或触发行为</param>
        /// <param name="pageIndex">初始页码</param>
        /// <param name="pageSize">页面大小</param>
        /// <returns>积分规则分页列表</returns>
        public static async Task<PagingList<T_PointRule>> List
            (string keyword, int pageIndex, int pageSize)
        {
            using(var db = DataBaseContext.GetDataBase("default"))
            {
                StringBuilder origin = new StringBuilder
                ("SELECT * FROM t_pointrule");
                if (!string.IsNullOrEmpty(keyword))
                {
                    origin.Append(" WHERE (F_PointCode LIKE '%" + keyword +
                        "%') OR (F_PointAction LIKE '%" + keyword + "%')");
                }
                origin.Append(" ORDER BY F_Sort=0,F_Sort,F_AddTime DESC");
                string sql = origin.ToString();
                var tmplist = await db.Sql(sql).ToList<T_PointRule>();
                var lst = tmplist.ListPage<T_PointRule>(pageIndex, pageSize);
                return new PagingList<T_PointRule>(lst)
                {
                    TotleCount = tmplist.Count
                };
            }
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="pointRuleKid">积分规则ID</param>
        /// <param name="status">启用状态</param>
        /// <returns>修改成功返回true</returns>
        public static async Task<bool> ModifyStatus(int pointRuleKid, bool status)
        {
            if (pointRuleKid <= 0)
                throw new Top.Web.WebApiException(Top.Web.ExceptionCode.ParameterError, "参数错误!");
            using(var db = DataBaseContext.GetDataBase("default"))
            {
                const string sql =
                    "UPDATE t_pointrule SET F_Status={0} WHERE Kid={1}";
                return await db.Sql(sql, status, pointRuleKid).ExecuteNonQuery() > 0;
            }
        }
        /// <summary>
        /// 根据PointCode获取已启用规则
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static async Task<T_PointRule> GetRuleByCode(string code)
        {
            using (var db = DataBaseContext.GetDataBase("default"))
            {
                const string sql =
                    "SELECT * FROM t_pointrule WHERE F_PointCode = {0} AND F_Status=1";
                return await db.Sql(sql, code).FirstOrDefault<T_PointRule>();
            }
        }
    }
}
